package com.reddys.rad.inventory.controller;



/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.math.BigInteger;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.util.Callback;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import com.reddys.rad.inventory.db.Product;
import com.reddys.rad.inventory.db.ProductCategory;
import com.reddys.rad.inventory.logic.ProductMasterLogic;
import com.reddys.rad.inventory.service.SalesService;
import com.reddys.rad.inventory.utils.EntityManagerImp;
import com.reddys.rad.inventory.utils.Utilities;


/**
 * FXML Controller class
 *
 * @author Arun
 */
public class ProductmasterController implements Initializable {

	Logger log  = Utilities.getLogger("ProductmasterController");
	@FXML
	private TextField productID;
	@FXML
	private TextField productName;
	@FXML
	private TextField itemCode;
	@FXML
	private TextField batchCode;
	@FXML
	private TextField uom;
	@FXML
	private TextField reorderValue;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableView productTable;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableProductID;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableProductName;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableItemCode;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableBatchCode;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableProductUOM;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableReorderValue;
	@SuppressWarnings("rawtypes")
	@FXML
	private ComboBox productCategory;
	@SuppressWarnings("rawtypes")
	@FXML
	private TableColumn tableproductCategory;

	EntityManager manager=EntityManagerImp.getEntityManager();


	/**
	 * Initializes the controller class.
	 */
	@Override
	public void initialize(URL url, ResourceBundle rb) {
		try{
			populateAllProducts();
			initializeProductCategrory();
			addEventHander();
		}catch(Exception e){
			e.printStackTrace();
			log.info(e.getMessage());

		}
	}


	@FXML
	public void save(ActionEvent event) {
		try{
			if(validateSave()){
				System.out.println("product" + productID.getText());
				Product product = new Product();
				Boolean flag=false;
				if(productID.getText()!=null && productID.getText().length()>0){
					product.setProductId(productID.getText());
					flag=true;
				}
				product.setProductDescription(productName.getText());
				product.setItemCode(itemCode.getText());
				product.setBatchCode(batchCode.getText());
				product.setStandardUom(uom.getText());
				product.setReorderLevel(new BigInteger(reorderValue.getText()));
				ProductCategory category = SalesService.getProductCategoryByDesc(productCategory.getSelectionModel().getSelectedItem().toString());
				product.setProductCategoryId(category.getProductCategoryId());
				Product product1;
				if(flag){
					product1=(Product) EntityManagerImp.merge(product);  
				}else {
					product1=(Product) EntityManagerImp.persist(product);   
				}

				productID.setText(product1.getProductId());
				populateAllProducts();
				Utilities.createDialog("Transaction Completed Successfully");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	@FXML
	public void clear(ActionEvent event) {
		productID.setText(null);
		productName.setText(null);
		itemCode.setText(null);
		batchCode.setText(null);
		uom.setText(null);
		reorderValue.setText(null);
		productCategory.setValue(null);
		populateAllProducts();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public  void populateProducttable(List<Product> list){
		ObservableList list2= FXCollections.observableArrayList();
		for(Product l:list){
			ObservableList list1= FXCollections.observableArrayList();
			list1.add(l.getProductId());
			list1.add(l.getProductDescription());
			list1.add(l.getItemCode());
			list1.add(l.getBatchCode());
			list1.add(l.getStandardUom());
			list1.add(l.getReorderLevel()!=null?l.getReorderLevel().toString():"");
			Query queryProductCategory = manager.createNamedQuery("ProductCategory.findByProductCategoryId");
			queryProductCategory.setParameter("productCategoryId", l.getProductCategoryId());
			List<ProductCategory> listProductCategory= (List<ProductCategory>) queryProductCategory.getResultList();

			if(listProductCategory.size()>0){
				ProductCategory productCategory = listProductCategory.get(0);
				list1.add(productCategory.getProductCategoryDescription());
			}


			System.out.println("----------"+l.getProductCategoryId());
			list2.add(list1);
		} 


		productTable.getItems().clear();;
		productTable.setItems(list2);
		System.out.println("heelooooooooooo"+list2.size());
		tableProductID.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty(cdf.getValue().get(0)!=null?cdf.getValue().get(0).toString():"");
			}



		});

		tableProductName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(1)!=null?cdf.getValue().get(1).toString():"");
			}



		});

		tableItemCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(2)!=null?cdf.getValue().get(2).toString():"");
			}



		});

		tableBatchCode.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(3)!=null?cdf.getValue().get(3).toString():"");
			}




		});

		tableProductUOM.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(4)!=null?cdf.getValue().get(4).toString():"");
			}



		});

		tableReorderValue.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(5)!=null?cdf.getValue().get(5).toString():"");
			}



		});
		tableproductCategory.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<String>,String>, ObservableValue<String>>(){

			@Override
			public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList<String>, String> cdf) {
				return new SimpleStringProperty( cdf.getValue().get(6)!=null?cdf.getValue().get(6).toString():"");
			}



		});
	}




	private boolean validateSave() {

		if(Utilities.isNull(productName.getText())){
			Utilities.createDialog("Please enter product name");
			return false;
		}
		if(Utilities.isNull(uom.getText())){
			Utilities.createDialog("Please enter UOM");
			return false;  
		}
		if(Utilities.isNull(reorderValue.getText())){
			Utilities.createDialog("Please enter re-order value");
			return false;  
		}
		String category = (String) productCategory.getSelectionModel().getSelectedItem();
		if(Utilities.isNull(category)){
			Utilities.createDialog("Please select product category");
			return false;  
		}
		return true;
	}
	
	@SuppressWarnings("unchecked")
	private void populateAllProducts(){
		Query query=manager.createNamedQuery("Product.findAll");
		List<Product> productList= (List<Product>) query.getResultList();
		populateProducttable(productList);
	}
	
	private void addEventHander() {
		productTable.setOnMouseClicked(new EventHandler<MouseEvent>() {

			@SuppressWarnings({ "rawtypes", "unchecked" })
			@Override
			public void handle(MouseEvent t) {
				ObservableList product=(ObservableList)productTable.getSelectionModel().getSelectedItem();
				productID.setText((String)product.get(0));
				productName.setText((String)product.get(1));
				itemCode.setText((String)product.get(2));
				batchCode.setText((String)product.get(3));
				uom.setText((String)product.get(4));
				reorderValue.setText((String)product.get(5));
				productCategory.setValue((String)product.get(6));
			}
		});
		
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void initializeProductCategrory() {
		ObservableList list=FXCollections.observableArrayList();
		list.addAll(ProductMasterLogic.getProductCategory());
		productCategory.setItems(list);
		productCategory.valueProperty().addListener(new ChangeListener() {
			@Override
			public void changed(ObservableValue arg0, Object arg1,
					Object arg2) {
				System.out.println("productCategory--------->"+productCategory.getSelectionModel().getSelectedItem());	
				Query productCategoryquery=manager.createNamedQuery("ProductCategory.findByProductCategoryDescription");
				productCategoryquery.setParameter("productCategoryDescription", productCategory.getSelectionModel().getSelectedItem());
				List<ProductCategory> productCategoryList= (List<ProductCategory>) productCategoryquery.getResultList();
				if(productCategoryList!=null && productCategoryList.size()>0){
					ProductCategory productCategory = productCategoryList.get(0);
					Query query=manager.createNamedQuery("Product.findByProductCategory");
					query.setParameter("productCategoryId", productCategory.getProductCategoryId());
					List<Product> productList= (List<Product>) query.getResultList();
					populateProducttable(productList);
				}

				
			}				
		});
	}


}
